package org.glxy.shop.service;

import org.glxy.shop.InventoryLogRepository;
import org.glxy.shop.ProductRepository;
import org.glxy.shop.dto.InventoryOperationRequest;
import org.glxy.shop.entity.InventoryLog;
import org.glxy.shop.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class InventoryService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private InventoryLogRepository inventoryLogRepository;

    // 执行库存操作
    public Product operateInventory(String productId, InventoryOperationRequest request) {
        // 查找商品
        Product product = productRepository.findById(productId).orElse(null);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        // 验证操作类型
        if (request.getOperationType() != 1 && request.getOperationType() != -1) {
            throw new RuntimeException("操作类型不正确，1表示入库，-1表示出库");
        }

        // 计算新的库存数量
        long newInventory = product.getInventory() + request.getOperationType() * request.getQuantity();

        // 检查出库时库存是否足够
        if (request.getOperationType() == -1 && newInventory < 0) {
            throw new RuntimeException("库存不足，无法出库");
        }

        // 更新商品库存
        product.setInventory(newInventory);
        productRepository.save(product);

        // 创建库存日志
        InventoryLog log = new InventoryLog(productId, request.getOperationType(), request.getQuantity(), request.getRemark());
        inventoryLogRepository.save(log);

        return product;
    }

    // 查询库存日志，按操作时间倒序排列（最新的在前）
    public Page<InventoryLog> getInventoryLogs(String productId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "operationTime"));
        return inventoryLogRepository.findByProductId(productId, pageable);
    }
}